import buffer from '@ohos.buffer';
import fileIo from '@ohos.file.fs';
import { danmaku } from './danmaku';
import { DOMParser } from '@ohos/xmldom';
import { danmakuType } from './models/danmakuType';
import { danmakuSize } from './models/danmakuSize';
import { danmakuPoolType } from './models/danmakuPoolType';

export class danmakuParser {
  static loadXmlFromFile(path: string): danmaku[] {
    fileIo.accessSync(path);
    let file = fileIo.openSync(path, fileIo.OpenMode.READ_ONLY);
    let stat = fileIo.statSync(file.fd);
    let stream = fileIo.fdopenStreamSync(file.fd, 'r');
    let arrayBuffer = new ArrayBuffer(stat.size);
    stream.readSync(arrayBuffer);
    let buf = buffer.from(arrayBuffer);
    stream.closeSync();
    if (file)
      fileIo.closeSync(file);
    return this.loadXmlFromString(buf.toString());
  }

  static loadXmlFromString(danmakusXml: string): danmaku[] {
    let list: danmaku[] = [];
    let doc = new DOMParser().parseFromString(danmakusXml, 'text/xml');
    let obj: any[] = doc.getElementsByTagName('i')?.getElementsByTagName('d');
    if (obj) {
      for (let item of obj) {
        var attributes: string = item.getAttribute("p")?.toString();
        var attributeList = attributes.split(',');
        let d = new danmaku();
        d.content = item.Value;
        d.senderUIDHash = attributeList[6];
        d.id = Number.parseInt(attributeList[7]);
        d.colour = Number.parseInt(attributeList[3]);
        d.sendTime = Number.parseInt(attributeList[4]);
        d.showTime = Number.parseFloat(attributeList[0]);
        d.type = Number.parseInt(attributeList[1]) as danmakuType;
        d.size = Number.parseInt(attributeList[2]) as danmakuSize;
        d.poolType = Number.parseInt(attributeList[5]) as danmakuPoolType;
        list.push(d);
      }
    }
    var i = 0;
    list = list.sort(d => d.showTime);
    list.forEach(d => {
      d.index = i;
      i++;
    });
    return list;
  }
}